import json

from urllib import parse
from support.sys.schedule import FilmSchedule
from support.utils.toolkit import Log
from http.server import HTTPServer,BaseHTTPRequestHandler

class MovieHttpServer(HTTPServer):
    def run(port):
        try:
            server = MovieHttpServer(('0.0.0.0', port), MovieResquest)
            server.serve_forever()
        except Exception as e:
            Log.e(str(e))
            server.socket.close
            server.server_close    

class MovieResquest(BaseHTTPRequestHandler):
    PARAM_ID = "ID"
    PARAM_NUM = "NUM"
    def log_message(self, format: str, *args):
        return   
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        lst = []
        res = parse.urlparse(self.path)
        if(res.path == "/list"):
            lst = FilmSchedule().getPlayLst()
        elif(res.path == "/info"):
            lst = FilmSchedule().getInfo()
        elif(res.path == "/poster"):
            id = 0
            num = 5
            for param in res.query.split("&"):
                p = param.split("=", 1)
                if(p[0].upper() == MovieResquest.PARAM_ID):id=p[1]
                if(p[0].upper() == MovieResquest.PARAM_NUM):num=int(p[1])
            if(num > 7): num = 7
            if(num < 1): num = 1
            if(id != 0):lst = FilmSchedule().getSnapshot(id, num)
        self.wfile.write(json.dumps(lst).encode())
        self.wfile.flush()
        return
